'use strict';

const whiteList = [
    /** @userAccount */
    'sendSMS',
    'loginPwd',
    'loginVer',
    'loginAdmin',
    'userPassword',
    'userInfoOther',
    /** @utilsFile */
    'uploadWebKey',
    'uploadWebSave',
    /** @other */
    'youanmi_dati_getjiangpin',
    'youanmi_dati_checkTotal'
];

module.exports = _ => {
    return async function verifyLogin(ctx, next) {
        const { jwr_ver } = ctx.app;
        const { url, token } = ctx.request;
        // 过滤params
        let url_split = url.split('/')[1];
        // 过滤query
        url_split = url_split.split('?')[0];
        let isWhiteList = false;
        ctx.body = {};
        // console.log(url, url_split, whiteList.indexOf(url_split));

        if (whiteList.indexOf(url_split) !== -1) {
            isWhiteList = true;
        }

        try {
            ctx.token = await ctx.app.decodeToken(token);
            const isOldToken = !ctx.token.jwr_ver || ctx.token.jwr_ver < jwr_ver;
            if (isOldToken && !isWhiteList) {
                return ctx.returnBody(403, '登录信息已过期, 请重新登录');
            }
        } catch (err) {
            if (!isWhiteList) {
                return ctx.returnBody(403, '请先登录');
            }
        }

        if (ctx.app.config.env === 'local') {
            ctx.body.middlewareToken = ctx.token;
        }

        await next();
    };
};
